﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GovernmentOfficeProject.LevelDataAccessModel;
using GovernmentOfficeProject.LevelBusinessLogic;
using GovernmentOfficeProject.SysTools;
using System.Text;
using System.Collections;

namespace GovernmentOfficeProject.LevelViewUI.admin
{
    public partial class UserManagerDetail : System.Web.UI.Page
    {
        decimal dclLoginUserID = -1;
        //这里单独获取用户对应的部门列表,和所有部门的列表做对比,设置listview的选中.
        decimal dclValueParameter = -1;
        string strUseParmeter = "noValue";
        static StringBuilder sbrValueCheck = new StringBuilder();
        
        BLL_USER userBLL = new BLL_USER();
        BLL_Department deptBLL = new BLL_Department();
        BLL_RoleManager roleBLL = new BLL_RoleManager();
        Entity_USER_User userEntity = null;
        List<Entity_USER_Department> userDeptList = null;
        List<Entity_USER_Department> allDeptList = null;
        List<Entity_USER_Role> userRoleList = null;
        List<Entity_USER_Role> allRoleList = null;
        bool blControlValueCheck = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            //权限判断
            if (SystemContext.CurrentUserID == 0 || SystemContext.IsAdmin == 0)
            {
                Response.Redirect("/LevelViewUI/admin/Login.htm?FromUrl=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri));
            }
            else
            {
                SystemContext.CurrentUserID = SystemContext.CurrentUserID;
                SystemContext.IsAdmin = 1;
            }
            dclLoginUserID = SysTools.SystemContext.CurrentUserID;
            dclValueParameter = Convert.ToDecimal(Request.QueryString["umdval"]);
            strUseParmeter = Convert.ToString(Request.QueryString["umduse"]).Trim();
            //获取当前用户.
            if (strUseParmeter.Equals("new"))
            {
                userEntity = new Entity_USER_User();
            }
            else
            {
                userEntity = userBLL.getUserByUserID(dclValueParameter);
            }
            userDeptList = deptBLL.getDeptListByUser(userEntity);       //获取当前用户对应的部门实体列表.
            userRoleList = roleBLL.getRoleListByUser(userEntity);       //获取当前用户对应的用户组(角色)实体列表.            
            allDeptList = deptBLL.getDeptList();                        //获取所有部门.            
            allRoleList = roleBLL.getRoleList();                        //获取所有角色.

            if (!Page.IsPostBack)
            {
                if (strUseParmeter.Equals("detail")&&dclValueParameter>0)    //如果是查看用户资料.
                {
                    if (userToLoad())   //加载用户信息到当前页面.
                    {
                        operationStateShow("用户信息加载完成.");
                    }
                    else
                    {
                        operationStateShow("sorry,Users fail to load!");
                    }
                }
                if (strUseParmeter.Equals("new"))       //如果是新建用户,隐藏角色和部门操作.
                {
                    setDeptAndRoleVisible(false);
                    btnSave.Text = "新   增";                    
                }
                else
                {                    
                    ListBoxDeptSettingValues();    //为部门赋值.
                    ListBoxRoleSettingValues();    //为用户组赋值.
                    setDeptAndRoleVisible(true);
                    btnSave.Text = "修   改";
                }
            }
            if (strUseParmeter.Equals("detail")&&dclValueParameter>0)
            {
                ListBoxDeptSettingValues();    //为部门赋值.
                ListBoxRoleSettingValues();    //为用户组赋值.
            }
        }

        /// <summary>
        /// 部门和角色相关控件的显示.
        /// </summary>
        /// <param name="controlVisible"></param>
        private void setDeptAndRoleVisible(bool controlVisible)
        {
            this.btnSelectDept.Visible = controlVisible;
            this.btnSelectRole.Visible = controlVisible;
            this.ListBoxDepts.Visible = controlVisible;
            this.ListBoxRoles.Visible = controlVisible;
            this.lblDepts.Visible = controlVisible;
            this.lblRoles.Visible = controlVisible;
        }

        /// <summary>
        /// 在左上角的lbl显示操作状态.
        /// </summary>
        /// <param name="strOSS"></param>
        private void operationStateShow(string strOSS)
        {
            this.lblOperationState.Text = "操作状态:";
            this.lblOperationState.Text = this.lblOperationState.Text + strOSS;
        }

        //strUseParmeter是detail时,处理页面加载用户信息.调用需提前判断并注意dclValueParameter必须是用户ID.
        private bool userToLoad()
        {
            bool flag = false;
            try
            {
                //获取用户信息
                this.txtLoginName.Text = userEntity.LoginName;
                this.txtLoginPWD.Text = userEntity.LoginPassword;
                this.txtRealName.Text = userEntity.RealName;
                this.rblSex.SelectedValue = userEntity.Sex.Trim();
                this.txtMobilePhone.Text = userEntity.MobilePhone;
                this.txtTelephony.Text = userEntity.Telephony;
                this.txtEmail.Text = userEntity.Email;
                this.txtQQ.Text = userEntity.QQ;
                this.txtWorkAddress.Text = userEntity.OfficeAddress;
                this.txtHomeAddress.Text = userEntity.HomeAddress;
                this.txtBackup.Text = userEntity.Backup1;
                this.rblUserState.SelectedValue = userEntity.RecordStatus.ToString();
                this.txtLastLoginDate.Text = userEntity.LastLoginTime.Trim();
                this.txtCreateUser.Text = new BLL_USER().getUserByUser(userEntity).LoginName;
                this.txtCreateDate.Text = userEntity.CreateDateTime.Trim();
                this.txtModifyUser.Text = new BLL_USER().getUserByUser(userEntity).LoginName;
                this.txtModifyUser.Text = userBLL.getUserByUserID(SystemContext.CurrentUserID).LoginName; 
                this.txtModifyDate.Text = userEntity.ModifyDateTime.Trim();
                flag = true;
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 为部门 ListBox赋值.
        /// </summary>
        public void ListBoxDeptSettingValues()
        {
        //↓为部门赋值: 给部门listbox赋值

            ArrayList arrListDeptName = new ArrayList();
            //以Map的形式保存用户所在的部门，方便查找
            Dictionary<decimal, Entity_USER_Department> userDeptMap = new Dictionary<decimal, Entity_USER_Department>();
            foreach (Entity_USER_Department userDept in userDeptList)
            {
                userDeptMap.Add(userDept.DeptID, userDept);
            }
            foreach (Entity_USER_Department allDept in allDeptList)
            {
                if (userDeptMap.ContainsKey(allDept.DeptID))
                {
                    allDept.Selected = true;
                    arrListDeptName.Add(allDept.DeptName);
                }
                else
                {
                    allDept.Selected = false;
                }                
            }
            ListBoxDepts.DataSource = arrListDeptName;
            ListBoxDepts.DataBind();            
        }

        /// <summary>
        /// 为用户组ListBox赋值.
        /// </summary>
        public void ListBoxRoleSettingValues()
        {
            //为用户组(角色)赋值:  
            //BLL_USER userBLL = new BLL_USER();
            //Entity_USER_User user = userBLL.getUserByUser(userEntity);
            //List<Entity_USER_Role> userRoleList = userBLL.getRoleByUser(user);//修改.-------------------------------------------
            //List<Entity_USER_Role> allRoleList = new BLL_RoleManager().getRoleList();
            ArrayList arrListRoleName = new ArrayList();
            Dictionary<decimal, Entity_USER_Role> userRoleMap = new Dictionary<decimal, Entity_USER_Role>();
            foreach (Entity_USER_Role userRole in userRoleList)
            {
                userRoleMap.Add(userRole.RoleID, userRole);
            }
            foreach (Entity_USER_Role allRole in allRoleList)
            {
                if (userRoleMap.ContainsKey(allRole.RoleID))
                {
                    allRole.Selected = true;
                    arrListRoleName.Add(allRole.RoleName);
                }
                else
                {
                    allRole.Selected = false;
                }
            }
            ListBoxRoles.DataSource = arrListRoleName;
            ListBoxRoles.DataBind();
        }

        //返回按钮的点击事件处理:
        protected void btnGoBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserManager.aspx",false);
            //Response.Redirect("UserManager.aspx?umuse=update", false);
        }

        //保存按钮的点击事件处理(部门和角色单独弹出页处理保存,无关此地儿,且注意了):
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (strUseParmeter.Equals("detail") && dclValueParameter > 0) //更新用户.
            {
                if (controlValueCheck())
                {
                    Entity_USER_User user = new Entity_USER_User();
                    user.LoginName = this.txtLoginName.Text.Trim();
                    user.LoginPassword = this.txtLoginPWD.Text.Trim();
                    user.RealName = this.txtRealName.Text.Trim();
                    user.Sex = this.rblSex.SelectedValue.Trim();
                    user.MobilePhone = this.txtMobilePhone.Text.Trim();
                    user.Telephony = this.txtTelephony.Text.Trim();
                    user.Email = this.txtEmail.Text.Trim();
                    user.QQ = this.txtQQ.Text.Trim();
                    user.OfficeAddress = this.txtWorkAddress.Text.Trim();
                    user.HomeAddress = this.txtHomeAddress.Text.Trim();
                    user.ModifyUserID = dclLoginUserID;  //*加入
                    user.ModifyDateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"); //*加入

                    user.Backup1 = this.txtBackup.Text.Trim();
                    user.RecordStatus = Convert.ToDecimal(this.rblUserState.SelectedValue.Trim());
                    bool blUpdateFlag = new BLL_USER().updateUserByUserID(dclValueParameter, user);
                    if (blUpdateFlag)
                    {
                        operationStateShow("更新用户信息成功.");
                    }
                    else
                    {
                        operationStateShow("系统错误:更新用户信息失败了!...");
                    }
                }
                else
                {
                    operationStateShow("更新失败-请检查输入值正确性.");
                }
            }
            if (strUseParmeter.Equals("new"))   //新建用户.
            {
                if (controlValueCheck())
                {
                    //operationStateShow()
                    Entity_USER_User user = new Entity_USER_User();
                    user.LoginName = this.txtLoginName.Text.Trim();
                    user.LoginPassword = this.txtLoginPWD.Text.Trim();
                    user.RealName = this.txtRealName.Text.Trim();
                    user.Sex = this.rblSex.SelectedValue.Trim();
                    user.MobilePhone = this.txtMobilePhone.Text.Trim();
                    user.Telephony = this.txtTelephony.Text.Trim();
                    user.Email = this.txtEmail.Text.Trim();
                    user.QQ = this.txtQQ.Text.Trim();
                    user.OfficeAddress = this.txtWorkAddress.Text.Trim();
                    user.HomeAddress = this.txtHomeAddress.Text.Trim();
                    user.CreateUserID = dclLoginUserID; //*加入
                    user.Backup1 = this.txtBackup.Text.Trim();
                    //如果是新增用户,"提示:请先保存用户后再进行部门和角色的操作."
                    //this.btnSelectDept.Attributes.Add("Readonly", "readonly"); 
                    user.RecordStatus = Convert.ToDecimal(this.rblUserState.SelectedValue.Trim());
                    bool blAdd = new BLL_USER().addUserByEntity(user);
                    if (blAdd)
                    {
                        operationStateShow("新增用户成功! ");
                    }
                    else
                    {
                        operationStateShow("系统错误:新增用户失败了!...");
                    }
                }
                else
                {
                    
                    operationStateShow("新增失败-请检查输入值正确性.");
                }
            }
        }

        //控件值验证        
        private bool controlValueCheck()
        {
            bool flag = true;
            this.lblMsLoginName.Text = "*";
            this.lblMsLoginPWD.Text = "*";
            this.lblMsMobilePhone.Text = "*";
            this.lblMsRealName.Text = "*";

            if (strUseParmeter.Equals("new"))
            {
                if (this.txtLoginName.Text.Length == 0)
                {
                    this.lblMsLoginName.Text = "*不能为空值.";
                    flag = false;
                }
                else if (this.txtLoginName.Text.Length < 5 || this.txtLoginName.Text.Length > 16)
                {
                    lblMsLoginName.Text = "*长度5-16字符.";
                    flag = false;
                }
                else
                {
                    Entity_USER_User userParameter = new Entity_USER_User();
                    userParameter.LoginName = this.txtLoginName.Text.Trim();
                    if (userBLL.getUserListByCondition(userParameter).Count > 0)
                    {
                        this.lblMsLoginName.Text = "*名称重复.";
                        flag = false;
                    }
                }

                if (this.txtMobilePhone.Text.Length != 11)
                {
                    this.lblMsMobilePhone.Text = "*必须11位.";
                    flag = false;
                }
                else
                {
                    Entity_USER_User userParameter = new Entity_USER_User();
                    userParameter.MobilePhone = this.txtMobilePhone.Text.Trim();
                    List<Entity_USER_User> userList = userBLL.getUserListByCondition(userParameter);
                    if (userList.Count > 0)
                    {
                        this.lblMsMobilePhone.Text = "*手机号重复.";
                        flag = false;
                    }
                }
            }

            if (strUseParmeter.Equals("detail") && dclValueParameter > 0)
            {
                if (this.txtLoginName.Text.Length == 0)
                {
                    this.lblMsLoginName.Text = "*不能为空值.";
                    flag = false;
                }
                else if (this.txtLoginName.Text.Length < 5 || this.txtLoginName.Text.Length > 16)
                {
                    lblMsLoginName.Text = "*长度5-16字符.";
                    flag = false;
                }
                else
                {
                    Entity_USER_User userEntity = userBLL.getUserByUserID(dclValueParameter);
                    List<Entity_USER_User> userList = userBLL.getAllUser();
                    //AppLog.Write("defaule:"+userList.Count.ToString(), AppLog.LogMessageType.Debug);
                    foreach (Entity_USER_User user in userList)
                    {
                        if (user.UserID==userEntity.UserID)
                        {
                            if (userList.Remove(user))
                            {
                                break;
                            }
                        }
                    }
                    //AppLog.Write("remove:" + userList.Count.ToString(), AppLog.LogMessageType.Debug);
                    foreach (Entity_USER_User user in userList)
                    {
                        if (this.txtLoginName.Text.Trim()==user.LoginName)
                        {
                            lblMsLoginName.Text = "*用户名重复.";
                            flag = false;
                            break;
                        }
                    }
                }
                if (this.txtMobilePhone.Text.Length == 0)
                {
                    this.lblMsMobilePhone.Text = "*不能为空值.";
                    flag = false;
                }
                else if (this.txtMobilePhone.Text.Length != 11)
                {
                    this.lblMsMobilePhone.Text = "*必须是11位.";
                    flag = false;
                }
                else
                {
                    Entity_USER_User userEntity = userBLL.getUserByUserID(dclValueParameter);
                    List<Entity_USER_User> userList = userBLL.getAllUser();
                    //AppLog.Write("defaule:"+userList.Count.ToString(), AppLog.LogMessageType.Debug);
                    foreach (Entity_USER_User user in userList)
                    {
                        if (user.UserID == userEntity.UserID)
                        {
                            if (userList.Remove(user))
                            {
                                break;
                            }
                        }
                    }
                    //AppLog.Write("remove:" + userList.Count.ToString(), AppLog.LogMessageType.Debug);
                    foreach (Entity_USER_User user in userList)
                    {
                        if (this.txtMobilePhone.Text.Trim() == user.MobilePhone)
                        {
                            this.lblMsMobilePhone.Text = "*手机号重复.";
                            flag = false;
                            break;
                        }
                    }
                }
            }

            if (this.txtLoginPWD.Text.Length == 0)
            {
                this.lblMsLoginPWD.Text = "*不能为空值.";
                flag = false;
            }
            else if (this.txtLoginPWD.Text.Length < 3)
            {
                this.lblMsLoginPWD.Text = "*密码至少3位.";
                flag = false;
            }

            if (this.txtRealName.Text.Length == 0)
            {
                this.lblMsRealName.Text = "*不能为空值.";
                flag = false;
            }
            else if (this.txtRealName.Text.Length < 2 || this.txtRealName.Text.Length > 10)
            {
                lblMsRealName.Text = "*长度2-10字符.";
                flag = false;
            }
            return flag;
        }
    }  
}
